import React, { useEffect, useState } from 'react';
import { Table, Tag, Button, Space, message, Modal, Form, Input, InputNumber, Select, Tooltip } from 'antd';
import { IJyCourse } from '../types/jy_course';
import { 
  BookOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  PlusOutlined, 
  EyeOutlined, 
  InfoCircleOutlined 
} from '@ant-design/icons';
import TextArea from 'antd/lib/input/TextArea';

/**
 * 课程列表组件
 * 
 * 展示教育培训系统的课程信息，支持分页、搜索、查看详情、新增、编辑和删除操作
 */
const CourseList: React.FC = () => {
  // 状态定义
  const [courses, setCourses] = useState<IJyCourse[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [total, setTotal] = useState<number>(0);
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(10);
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [detailModalVisible, setDetailModalVisible] = useState<boolean>(false);
  const [currentCourse, setCurrentCourse] = useState<IJyCourse | null>(null);
  const [form] = Form.useForm();

  // 模拟从API获取数据
  const fetchCourses = async (page: number, size: number) => {
    setLoading(true);
    try {
      // 实际应用中应替换为真实的API调用
      // const response = await axios.get('/api/courses', { params: { page, size } });
      // 模拟数据
      setTimeout(() => {
        const mockCourses: IJyCourse[] = Array(10).fill(0).map((_, index) => ({
          id: `course-${1000 + index + (page - 1) * size}`,
          name: `课程${index + 1 + (page - 1) * size}`,
          sort: index + 1,
          duration: (index + 1) * 1800, // 以秒为单位
          intro: `这是关于课程${index + 1 + (page - 1) * size}的介绍内容，包含了课程的主要内容和学习目标。`,
          teacher: `讲师${(index % 5) + 1}`,
          cover: `https://example.com/images/course-${index + 1}.jpg`,
          remark: index % 2 === 0 ? `课程${index + 1}备注信息` : '',
          del_flag: 0,
          create_by: 1,
          create_name: 'admin',
          create_time: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString(),
          update_by: 1,
          update_time: new Date().toISOString(),
          difficulty: (index % 3 + 1).toString(), // 1-初级，2-中级，3-高级
          enable_random_attendance: index % 3 === 0 ? 1 : 0, // 是否启用随机考勤
        }));
        
        setCourses(mockCourses);
        setTotal(100); // 模拟总数
        setLoading(false);
      }, 500);
    } catch (error) {
      console.error('获取课程列表失败:', error);
      message.error('获取课程列表失败，请稍后重试');
      setLoading(false);
    }
  };

  // 页面加载时获取数据
  useEffect(() => {
    fetchCourses(currentPage, pageSize);
  }, [currentPage, pageSize]);

  // 处理分页变化
  const handleTableChange = (pagination: any) => {
    setCurrentPage(pagination.current);
    setPageSize(pagination.pageSize);
  };

  // 打开课程详情模态框
  const handleViewDetails = (course: IJyCourse) => {
    setCurrentCourse(course);
    setDetailModalVisible(true);
  };

  // 打开编辑模态框
  const handleEdit = (course: IJyCourse) => {
    setCurrentCourse(course);
    form.setFieldsValue({
      ...course,
      duration: course.duration ? course.duration / 60 : 0, // 转换为分钟显示
    });
    setModalVisible(true);
  };

  // 打开新增模态框
  const handleAdd = () => {
    setCurrentCourse(null);
    form.resetFields();
    setModalVisible(true);
  };

  // 处理删除
  const handleDelete = (courseId: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除此课程吗？此操作不可恢复。',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        // 实际应用中应替换为真实的API调用
        // await axios.delete(`/api/courses/${courseId}`);
        message.success('课程删除成功');
        fetchCourses(currentPage, pageSize);
      }
    });
  };

  // 处理表单提交
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      
      // 将分钟转换回秒
      const submittedData = {
        ...values,
        duration: values.duration * 60,
      };
      
      if (currentCourse) {
        // 更新课程
        // await axios.put(`/api/courses/${currentCourse.id}`, submittedData);
        message.success('课程信息更新成功');
      } else {
        // 新增课程
        // await axios.post('/api/courses', submittedData);
        message.success('课程添加成功');
      }
      
      setModalVisible(false);
      fetchCourses(currentPage, pageSize);
    } catch (error) {
      console.error('表单提交失败:', error);
    }
  };

  // 格式化时长显示
  const formatDuration = (seconds: number) => {
    if (!seconds) return '0分钟';
    
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    
    if (hours > 0) {
      return `${hours}小时${minutes > 0 ? ` ${minutes}分钟` : ''}`;
    }
    return `${minutes}分钟`;
  };

  // 获取难度等级标签
  const getDifficultyTag = (difficulty: string) => {
    switch (difficulty) {
      case '1':
        return <Tag color="green">初级</Tag>;
      case '2':
        return <Tag color="blue">中级</Tag>;
      case '3':
        return <Tag color="purple">高级</Tag>;
      default:
        return <Tag>未知</Tag>;
    }
  };

  // 表格列定义
  const columns = [
    {
      title: '课程名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: IJyCourse) => (
        <Space>
          <BookOutlined />
          <a onClick={() => handleViewDetails(record)}>{text}</a>
        </Space>
      )
    },
    {
      title: '讲师',
      dataIndex: 'teacher',
      key: 'teacher',
      width: 120,
    },
    {
      title: '时长',
      dataIndex: 'duration',
      key: 'duration',
      width: 120,
      render: (duration: number) => formatDuration(duration)
    },
    {
      title: '难度等级',
      dataIndex: 'difficulty',
      key: 'difficulty',
      width: 100,
      render: (difficulty: string) => getDifficultyTag(difficulty)
    },
    {
      title: '随机考勤',
      dataIndex: 'enable_random_attendance',
      key: 'enable_random_attendance',
      width: 100,
      render: (value: number) => (
        value === 1 ? <Tag color="green">已启用</Tag> : <Tag color="default">未启用</Tag>
      )
    },
    {
      title: '排序',
      dataIndex: 'sort',
      key: 'sort',
      width: 80,
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      key: 'create_time',
      width: 180,
      render: (time: string) => new Date(time).toLocaleString()
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_: any, record: IJyCourse) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button 
              icon={<EyeOutlined />} 
              size="small"
              onClick={() => handleViewDetails(record)}
            />
          </Tooltip>
          <Tooltip title="编辑">
            <Button 
              type="primary" 
              icon={<EditOutlined />} 
              size="small"
              onClick={() => handleEdit(record)}
            />
          </Tooltip>
          <Tooltip title="删除">
            <Button 
              danger 
              icon={<DeleteOutlined />} 
              size="small"
              onClick={() => handleDelete(record.id as string)}
            />
          </Tooltip>
        </Space>
      ),
    },
  ];

  return (
    <div className="course-list-container">
      <div className="table-operations" style={{ marginBottom: 16 }}>
        <Button 
          type="primary" 
          icon={<PlusOutlined />}
          onClick={handleAdd}
        >
          新增课程
        </Button>
      </div>
      
      <Table
        columns={columns}
        dataSource={courses}
        rowKey="id"
        pagination={{
          current: currentPage,
          pageSize: pageSize,
          total: total,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条记录`
        }}
        loading={loading}
        onChange={handleTableChange}
      />

      {/* 课程详情模态框 */}
      <Modal
        title="课程详情"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>
            关闭
          </Button>
        ]}
        width={700}
      >
        {currentCourse && (
          <div className="course-detail">
            <h2>{currentCourse.name}</h2>
            
            <div className="course-info" style={{ marginBottom: 20 }}>
              <p>
                <Space>
                  <Tag color="blue">讲师: {currentCourse.teacher}</Tag>
                  <Tag color="green">时长: {formatDuration(currentCourse.duration || 0)}</Tag>
                  {getDifficultyTag(currentCourse.difficulty || '1')}
                  {currentCourse.enable_random_attendance === 1 && 
                    <Tag color="orange">随机考勤</Tag>
                  }
                </Space>
              </p>
            </div>
            
            <div className="course-cover" style={{ marginBottom: 20 }}>
              {currentCourse.cover && (
                <img 
                  src={currentCourse.cover} 
                  alt={currentCourse.name} 
                  style={{ maxWidth: '100%', maxHeight: 300 }}
                />
              )}
            </div>
            
            <div className="course-intro">
              <h3>课程介绍</h3>
              <p>{currentCourse.intro || '暂无介绍'}</p>
            </div>
            
            {currentCourse.remark && (
              <div className="course-remark" style={{ marginTop: 20 }}>
                <h3>备注</h3>
                <p>{currentCourse.remark}</p>
              </div>
            )}
            
            <div className="course-meta" style={{ marginTop: 20 }}>
              <p>创建人: {currentCourse.create_name}</p>
              <p>创建时间: {new Date(currentCourse.create_time || '').toLocaleString()}</p>
              <p>更新时间: {new Date(currentCourse.update_time || '').toLocaleString()}</p>
            </div>
          </div>
        )}
      </Modal>

      {/* 新增/编辑课程模态框 */}
      <Modal
        title={currentCourse ? '编辑课程' : '新增课程'}
        open={modalVisible}
        onOk={handleSubmit}
        onCancel={() => setModalVisible(false)}
        width={700}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          name="courseForm"
          initialValues={{
            del_flag: 0,
            difficulty: '1',
            enable_random_attendance: 0,
            sort: 1,
          }}
        >
          <Form.Item
            name="name"
            label="课程名称"
            rules={[{ required: true, message: '请输入课程名称' }]}
          >
            <Input placeholder="请输入课程名称" />
          </Form.Item>
          
          <Form.Item
            name="teacher"
            label="讲师"
            rules={[{ required: true, message: '请输入讲师姓名' }]}
          >
            <Input placeholder="请输入讲师姓名" />
          </Form.Item>
          
          <Form.Item
            name="duration"
            label="课程时长(分钟)"
            rules={[{ required: true, message: '请输入课程时长' }]}
            tooltip="请输入课程时长，单位为分钟"
          >
            <InputNumber min={1} style={{ width: '100%' }} />
          </Form.Item>
          
          <Form.Item
            name="difficulty"
            label="难度等级"
          >
            <Select>
              <Select.Option value="1">初级</Select.Option>
              <Select.Option value="2">中级</Select.Option>
              <Select.Option value="3">高级</Select.Option>
            </Select>
          </Form.Item>
          
          <Form.Item
            name="enable_random_attendance"
            label={
              <span>
                随机考勤
                <Tooltip title="启用后，学习该课程时会随机要求学员进行考勤签到">
                  <InfoCircleOutlined style={{ marginLeft: 8 }} />
                </Tooltip>
              </span>
            }
          >
            <Select>
              <Select.Option value={0}>不启用</Select.Option>
              <Select.Option value={1}>启用</Select.Option>
            </Select>
          </Form.Item>
          
          <Form.Item
            name="sort"
            label="排序"
            tooltip="数值越小排序越靠前"
          >
            <InputNumber min={1} style={{ width: '100%' }} />
          </Form.Item>
          
          <Form.Item
            name="cover"
            label="封面图片"
          >
            <Input placeholder="请输入封面图片URL" />
          </Form.Item>
          
          <Form.Item
            name="intro"
            label="课程介绍"
          >
            <TextArea rows={4} placeholder="请输入课程介绍" />
          </Form.Item>
          
          <Form.Item
            name="remark"
            label="备注"
          >
            <TextArea rows={2} placeholder="请输入备注信息" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default CourseList; 